<template>
  <div class="security-inspection-page">
    <div class="breadcrumb">
      <Breadcrumb :data="breadcrumbData"></Breadcrumb>
    </div>
    <main>
      <div class="echarts-container">
        <div class="inspection-type">
          <div class="search-container">
            <h3>安全类型占比</h3>
            <div class="search-btn">
              <el-date-picker
                v-model="typeDate"
                size="mini"
                :format="typeFormat"
                :type="typeDateId"
                placeholder="选择日期">
              </el-date-picker>
              <ul class="date-btns">
                <li :class="typeDateId === 'month' ? 'active' : ''" @click="handleTypeDateClick('month')">按周</li>
                <li :class="typeDateId === 'year' ? 'active' : ''" @click="handleTypeDateClick('year')">按月</li>
              </ul>
            </div>
          </div>
          <echarts-base :options="typeOptions"></echarts-base>
        </div>
        <div class="inspection-type">
          <div class="search-container">
            <h3>安全整改统计</h3>
            <div class="search-btn">
              <el-date-picker
                v-model="statisticsDate"
                size="mini"
                :type="statisticsDateId"
                :format="statisticsFormat"
                placeholder="选择日期">
              </el-date-picker>
              <ul class="date-btns">
                <li :class="statisticsDateId === 'month' ? 'active' : ''" @click="handleDateClick('month')">按周</li>
                <li :class="statisticsDateId === 'year' ? 'active' : ''" @click="handleDateClick('year')">按月</li>
              </ul>
            </div>
          </div>
          <echarts-base :options="rectificationOptions"></echarts-base>
        </div>
        <div class="inspection-type problem">
          <p>问题总数：<span>{{ totalDetails.rectified + totalDetails.unRectified }}</span>个</p>
          <p>未整改数：<span>{{ totalDetails.unRectified }}</span>个</p>
          <p>已整改数：<span>{{ totalDetails.rectified }}</span>个</p>
          <p>整改率：<span>
            {{ parseFloat((totalDetails.rectified / (totalDetails.rectified + totalDetails.unRectified)) * 100).toFixed(2) }}
          </span>%</p>
        </div>
        <div class="inspection-type news">
          <div class="system-news news-item">
            <div class="title">系统消息</div>
            <div v-if="!newsList.length" class="news-empty">
              <i class="iconfont iconwushuju"></i>
              <p>暂无消息</p>
            </div>
            <ul v-else>
              <li v-for="(item, index) in newsList" :key="index" @click="setSheet">
                {{ item }}
              </li>
            </ul>
            <el-pagination
              v-if="systemTotal > 10"
              small
              :page-size="systemPageSize"
              :current-page="systemPageNo"
              layout="total, sizes, prev, pager, next, jumper"
              :total="systemTotal"
              @size-change="handleSystemSizeChange"
              @current-change="handleSystemCurrentChange"
            />
          </div>
        </div>
      </div>
      <div class="table-container">
        <div class="search-container">
          <span class="title">整改详情</span>
          <div class="search-content">
            <label>内容搜索：</label>
            <el-input
              placeholder="请输入"
              v-model="searchValue"
              @blur="handleSearch"
              @keydown.native.enter="handleSearch">
            </el-input>
          </div>
          <div class="search-content">
            <label>日期搜索：</label>
            <el-date-picker
              v-model="searchDate"
              value-format="yyyy-MM-dd"
              type="date"
              placeholder="选择日期"
              @change="handleSearch">
            </el-date-picker>
          </div>
        </div>
        <el-table
          class="table-content"
          v-loading="tableLoading"
          element-loading-custom-class="custom-load"
          :data="qualityList"
          style="width: 100%">
          <el-table-column prop="sender" label="发送人"></el-table-column>
          <el-table-column prop="location" label="位置"></el-table-column>
          <el-table-column prop="problem" label="整改详情" show-overflow-tooltip></el-table-column>
          <el-table-column label="检查类型">
            <template slot-scope="scope">
              <span>{{ scope.row.checktype && scope.row.checktype.name || '' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="levelStr" label="严重程度"></el-table-column>
          <el-table-column prop="stateStr" label="状态"></el-table-column>
          <el-table-column label="图片">
            <template slot-scope="scope">
              <div class="img-contianer" v-if="Array.isArray(setImage(scope.row))">
                <el-image
                  class="img"
                  lazy
                  :scroll-container="scrollDom"
                  :src="setImage(scope.row)[0]"
                  :preview-src-list="setImage(scope.row)">
                </el-image>
                <i class="el-icon-picture img-icon">
                  <span>{{ setImage(scope.row).length }}</span>
                </i>
              </div>
              <el-image
                v-else
                class="img"
                lazy
                :scroll-container="scrollDom"
                :src="setImage(scope.row)"
                :preview-src-list="[setImage(scope.row)]">
              </el-image>
            </template>
          </el-table-column>
          <el-table-column prop="created" label="发起时间">
            <template slot-scope="scope">
              {{ scope.row.created ? $moment(scope.row.created).format('yyyy-MM-DD HH:mm:ss') : ''}}
            </template>
          </el-table-column>
          <el-table-column prop="deadline" label="整改时间">
            <template slot-scope="scope">
              {{ scope.row.deadline ? $moment(scope.row.deadline).format('yyyy-MM-DD HH:mm:ss') : ''}}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120">
            <template slot-scope="scope">
              <i v-if="hasTableDetail" class="iconfont iconchakan" @click="handleLook(scope.row)"></i>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          v-if="total > 10"
          :page-size="pageSize"
          :current-page="pageNo"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </main>
    <!--查看安全巡查-->
    <rectification-model
      :visible="visible"
      :options="modelOptions"
      @cancel="visible = false">
    </rectification-model>
    <!--历史消息-->
    <historical-news
      :visible="newsVisible"
      @cancel="newsVisible = false">
    </historical-news>
    <!--整改单-->
    <rectification-sheet-model
      :visible="sheetVisible"
      @cancel="sheetVisible = false">
    </rectification-sheet-model>
  </div>
</template>

<script>
import echartsBase from '@/components/echarts/base';
import Breadcrumb from '@/components/public/Breadcrumb';
import rectificationModel from '@/components/project/security/rectificationModel';
import HistoricalNews from '@/components/project/security/HistoricalNews';
import RectificationSheetModel from '@/components/project/security/RectificationSheetModel';

// 安全检查-隐患排查及治理
export default {
  data() {
    return {
      // 面包屑数据
      breadcrumbData: [
        {
          name: '安全管理',
        },
        {
          name: '隐患排查及治理'
        }
      ],
      // 整改总数
      totalDetails: {},
      // 安全类型搜索时间
      typeDate: '',
      typeDateId: 'year',
      typeFormat: '',
      typeValueFormat: null,
      typeEchartsData: {
        legend: [],
        data: []
      },
      // 统计搜索时间
      statisticsDate: '',
      statisticsDateId: 'year',
      statisticsFormat: '',
      statisticsValueFormat: null,
      // 安全检查
      qualityList: [],
      // 安全类型占比图表数据
      typeOptionsseries: [],
      // 整改统计图表数据
      rectificationSeries: {
        series: [],
        xAxisData: [],
        legend: []
      },
      // 内容搜索项
      searchValue: '',
      // 日期搜索项
      searchDate: '',
      tableLoading: false,
      total: 0,
      pageSize: 10,
      pageNo: 1,
      // 是否展示整改详情弹框
      visible: false,
      // 弹框数据
      modelOptions: {},
      newsVisible: false,
      sheetVisible: false,
      // 消息通知
      newsList: [],
      systemPageSize: 10,
      systemPageNo: 1,
      systemTotal: 0,
      scrollDom: null
    };
  },
  computed: {
    // 安全占比
    qualityProportion() {
      return [];
    },
    // 安全类型占比图表数据
    typeOptions() {
      return {
        textStyle: {
          color: '#fff'
        },
        // legend: {
        //   data: this.typeEchartsData.legend,
        //   bottom: 10,
        //   textStyle: {
        //     color: '#fff'
        //   }
        // },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b} : {c} ({d}%)'
        },
        series: [
          {
            name: '安全类型占比',
            type: 'pie',
            radius: '55%',
            label: {
              color: '#fff',
              formatter: '{b}: {d}%'
            },
            data: this.typeEchartsData.data,
            // itemStyle: {
            //   color: 'rgb(85, 201, 246)'
            // },
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      };
    },
    // 安全整改统计
    rectificationOptions() {
      return {
        // title: {
        //   text: '安全整改统计',
        //   textStyle: {
        //     color: '#fff'
        //   }
        // },
        textStyle: {
          color: '#fff'
        },
        dataZoom: [
          {
            type: 'inside',
            start: 0,
            minValueSpan: 5,
            zoomLock: false
          }
        ],
        legend: {
          data: this.rectificationSeries.legend,
          bottom: 10,
          textStyle: {
            color: '#fff'
          }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        xAxis: {
          type: 'category',
          data: this.rectificationSeries.xAxisData,
          axisTick: {
            alignWithLabel: true
          }
        },
        yAxis: {
          type: 'value',
          axisLine: {
            show: false
          },
          // 刻度
          axisTick: {
            show: false
          }
        },
        series: this.rectificationSeries.series
      };
    },
    projectName() {
      return this.$store.state.currentProjectInfo.projectName;
    },
    projectId() {
      return this.$store.state.currentProjectId;
    }
  },
  watch: {
    typeDate(value) {
      this.setTypeDate(value);
      this.getSecurityLevelList();
    },
    statisticsDate(value) {
      this.setStatisticsDate(value);
      this.getSecurityStateList();
    }
  },
  created() {
    this.setTypeDate();
    this.setStatisticsDate();
    this.getSecurityList();
    this.getSecurityStateList();
    this.getSecurityLevelList();
    this.getSecurityStateNum();
    this.getSecuritySystemMessage();
  },
  mounted() {
    this.scrollDom = document.querySelector('.el-table__body-wrapper');
  },
  components: {
    Breadcrumb,
    echartsBase,
    HistoricalNews,
    rectificationModel,
    RectificationSheetModel
  },
  methods: {
    // 安全列表数据
    async getSecurityList() {
      this.tableLoading = true;
      const { success, data: { data }} = await this.$Model.getSecurityList({
        projectId: this.projectId,
        pageNum: this.pageNo,
        pageSize: this.pageSize,
        name: this.searchValue,
        queryDate: this.searchDate
      });
      this.tableLoading = false;
      if (success && data && Array.isArray(data.list)) {
        this.total = data.total || 0;
        this.qualityList = this.setQualityList(data.list);
      }
    },
    // 获取安全类型占比数据
    async getSecurityLevelList() {
      const { success, data: { data }} = await this.$Model.getSecurityLevelList({
        projectId: this.projectId,
        type: this.typeDateId === 'month' ? '1' : '2',
        queryTime: this.typeValueFormat
      });
      if (success && data) {
        this.setTypeList(data);
      }
    },
    // 获取问题总数
    async getSecurityStateNum() {
      const { success, data: { data }} = await this.$Model.getSecurityStateNum({
        projectId: this.projectId
      });
      if (success && data) {
        this.totalDetails = data;
      }
    },
    // 获取安全整改统计数据
    async getSecurityStateList() {
      const { success, data: { data }} = await this.$Model.getSecurityStateList({
        type: this.statisticsDateId === 'month' ? '1' : '2',
        queryTime: this.statisticsValueFormat,
        projectId: this.projectId
      });
      if (success && Array.isArray(data)) {
        this.setRectificationSeries(data);
      }
    },
    // 获取系统消息
    async getSecuritySystemMessage() {
      const { success, data: { data }} = await this.$Model.getSecuritySystemMessage({
        pageSize: this.systemPageSize,
        pageNum: this.systemPageNo,
        projectId: this.projectId
      });
      if (success && data) {
        this.newsList = data || [];
      }
    },
    /**
     * 设置整改统计echarts数据
     * @param data {Array}
     */
    setRectificationSeries(data) {
      const setConfig = (name, colorList = [], list = []) => {
        return {
          name,
          type: 'bar',
          barGap: 0,
          data: list,
          itemStyle: {
            color: new this.$echarts.graphic.LinearGradient(
              0, 0, 0, 1,
              [
                {
                  offset: 0,
                  color: colorList[0] || 'rgba(81, 202, 216, 1)'
                },
                {
                  offset: 1,
                  color: colorList[1] || 'rgba(81, 202, 216, 0.3)'
                }
              ]
            )
          }
        };
      };
      const result = {
        series: [],
        xAxisData: [],
        legend: []
      };
      data && data.forEach(item => {
        const { month, week, stateList } = item;
        result.xAxisData.push(this.statisticsDateId === 'year' ? month : week);
        stateList.forEach(val => {
          const { stateName, num } = val;
          const newNum = isNaN(num) ? 0 : Number(num);
          const currentVal = result.series.find(v => v.name === stateName);
          if (currentVal) {
            currentVal.data.push(newNum);
            return;
          }
          const colorList = result.series.length
            ? ['rgba(226, 145, 184, 1)', 'rgba(55, 142, 235, 1)']
            : [];
          result.series.push(setConfig(stateName, colorList, [newNum]));
        });
      });
      result.legend = result.series.map(item => item.name);
      this.rectificationSeries = result;
    },
    /**
     * 安全类型占比
     * @param type {String} 切换类型
     */
    handleTypeDateClick(type) {
      this.typeFormat = type === 'year' ? 'yyyy' : 'yyyy-MM';
      this.typeDateId = type;
      this.setTypeDate();
      this.getSecurityLevelList();
    },
    /**
     * 安全整改统计
     * @param type {String} 切换类型
     */
    handleDateClick(type) {
      this.statisticsFormat = type === 'year' ? 'yyyy' : 'yyyy-MM';
      this.statisticsDateId = type;
      this.setStatisticsDate();
      this.getSecurityStateList();
    },
    /**
     * 修改类型占比时间参数
     * @param value {?Date}
     */
    setTypeDate(value) {
      const timeStamp = (value || this.typeDate || new Date()).getTime();
      const formatType = this.typeDateId === 'year' ? 'yyyy' : 'yyyy-MM';
      this.typeValueFormat = this.$moment(timeStamp).format(formatType);
    },
    /**
     * 修改整改统计时间参数
     * @param value {?Date}
     */
    setStatisticsDate(value) {
      const timeStamp = (value || this.statisticsDate || new Date()).getTime();
      const formatType = this.statisticsDateId === 'year' ? 'yyyy' : 'yyyy-MM';
      this.statisticsValueFormat = this.$moment(timeStamp).format(formatType);
    },
    /**
     * 设置安全巡查数据
     * @param list {Array} 原始数据
     */
    setQualityList(list) {
      if (!Array.isArray(list)) return [];
      return list.map(item => {
        const {
          checkman,
          updated,
          created,
          checkdate,
          deadline,
          state,
          publisher,
          level,
          checktype,
          rectifyman
        } = item;
        const setName = (value) => {
          if (Array.isArray(value) && value.length) {
            return value.length > 1
              ? value.reduce((pre, next) => `${pre.name}${'、'}${next.name}`)
              : value[0].name;
          }
          return '';
        };
          // 设置时间格式
        const setTime = (value) => {
          if (value && value['$date']) {
            const time = value['$date']['$numberLong'];
            if (time) {
              return this.$moment(Number(time)).format('yyyy-MM-DD HH:mm:ss');
            }
          }
          return '';
        };
        return {
          ...item,
          levelStr: level && level.name || '', // 严重程度
          stateStr: state && state.name || '', // 状态
          checktypeStr: checktype && checktype.name || '', // 检查类型
          sender: publisher && publisher.name || '', // 发送人
          rectifymanStr: setName(rectifyman), // 整改人
          checkman: setName(checkman), // 检查人
          uploadDate: setTime(updated), // 上传时间
          createdDate: setTime(created), // 创建时间
          checkTime: setTime(checkdate), // 检查日期
          deadlineDate: setTime(deadline) // 最终整改期限
        };
      });
    },
    /**
     * 设置安全类型占比图表数据
     * @param data {Array}
     */
    setTypeList(data) {
      const result = {
        legend: [],
        data: []
      };
      data && data.forEach(item => {
        const { checkList = [] } = item;
        checkList && checkList.forEach(val => {
          const { dangerType, num } = val;
          const currentItem = result.data.find(v => v.name === dangerType);
          const levelNum = isNaN(num) ? 0 : Number(num);
          if (currentItem) {
            currentItem.value += levelNum;
            return;
          }
          result.data.push({
            name: dangerType,
            value: levelNum
          });
        });
      });
      result.data = result.data.filter(item => item.value);
      result.legend = result.data.map(item => item.name);
      this.typeEchartsData = result;
    },
    /**
     * 设置图片
     * @param row {Object}
     */
    setImage(row) {
      if (Array.isArray(row.img)) {
        if (row.img.length > 1) {
          return row.img.map(item => `${this.$configs.ossUrl}${item}`);
        }
        return `${this.$configs.ossUrl}${row.img[0]}`;
      }
      return `${this.$configs.ossUrl}${row.img}`;
    },
    /**
     * 查看、回复整改单
     * @param type {String} 消息类型
     */
    setSheet(type) {
      // this.sheetVisible = true;
    },
    /**
     * 查看历史记录
     * @param type {String} 消息类型
     */
    handleView(type) {
      this.newsVisible = true;
    },
    /**
     * pageSize 改变时会触发
     * @param pageSize 每页条数
     */
    handleSizeChange(pageSize) {
      this.pageNo = 1;
      this.pageSize = pageSize;
      this.getSecurityList();
    },
    /**
     * currentPage 改变时会触发
     * @param pageNo 当前页
     */
    handleCurrentChange(pageNo) {
      this.pageNo = pageNo;
      this.getSecurityList();
    },
    /**
     * pageSize 改变时会触发
     * @param pageSize 每页条数
     */
    handleSystemSizeChange(pageSize) {
      this.systemPageNo = 1;
      this.systemPageSize = pageSize;
      this.getSecuritySystemMessage();
    },
    /**
     * currentPage 改变时会触发
     * @param pageNo 当前页
     */
    handleSystemCurrentChange(pageNo) {
      this.systemPageNo = pageNo;
      this.getSecuritySystemMessage();
    },
    /**
     * 搜索
     */
    handleSearch() {
      this.getSecurityList();
    },
    /**
     * 查看整改详情
     * @param row {Object}
     */
    handleLook(row) {
      this.modelOptions = { ...row };
      this.visible = true;
    }
  }
};
</script>

<style scoped lang="scss">
  @import '../../../assets/styles/table';

  .security-inspection-page {
    width: 100%;
    height: 100%;
    background-color: $baseBg;
    color: #fff;
    main {
      width: 100%;
      height: calc(100% - 40px);
      padding: 20px;
      border-radius: 10px;
    }
    .echarts-container {
      height: 300px;
      width: 100%;
      display: flex;
      justify-content: space-between;
      align-items: center;
      .inspection-type {
        width: 24%;
        height: 100%;
        padding: 10px;
        background-color: $mainBg;
        border-radius: 10px;
        position: relative;
        .search-container {
          position: absolute;
          top: 0;
          left: 0;
          width: 100%;
          height: 40px;
          z-index: 8;
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 10px 10px 0;
          .search-btn {
            width: 300px;
            margin-left: 10px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            .date-btns {
              width: 80px;
              height: 30px;
              display: flex;
              justify-content: center;
              align-items: center;
              border-radius: 20px;
              margin-left: 20px;
              li {
                width: 40px;
                height: 100%;
                display: flex;
                justify-content: center;
                align-items: center;
                font-size: 13px;
                background-color: rgba(161, 161, 161, .5);
                cursor: pointer;
                transition: all .3s;
                z-index: 1;
                &.active {
                  background-color: $successBtn;
                }
                &:nth-child(1) {
                  border-radius: 5px 0 0 5px;
                }
                &:nth-last-child(1) {
                  border-radius: 0 5px 5px 0;
                }
              }
            }
          }
        }
        &.problem {
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: center;
          padding: 20px 10px;
          p {
            width: 100%;
            margin: 10px;
            font-size: 24px;
            padding: 0 50px;
            display: flex;
            align-items: center;
            span {
              font-family: font-lcd;
              color: $mainColor;
              text-shadow: 0 1px 13px $mainColor;
              font-size: 40px;
              display: inline-block;
              margin: 0 10px 0 20px;
            }
          }
        }
        &.news {
          padding: 10px 20px;
          .header {
            width: 100%;
            height: 30px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            font-weight: bold;
            font-size: 16px;
            margin-bottom: 5px;
          }
          .news-item {
            height: 100%;
            .title {
              height: 30px;
              display: flex;
              justify-content: center;
              align-items: center;
              background-color: $lightBtnBg;
              font-size: 14px;
              border-radius: 5px;
              position: relative;
              i {
                position: absolute;
                right: 10px;
                top: 6px;
                font-size: 13px;
                cursor: pointer;
              }
            }
            ul {
              height: calc(100% - 70px);
              overflow: auto;
              li {
                font-size: 14px;
                padding: 2px 5px;
                cursor: pointer;
                border-radius: 5px;
                transition: color .2s;
                &:hover {
                  color: $mainColor;
                }
              }
            }
            .news-empty {
              width: 100%;
              height: 100%;
              display: flex;
              flex-direction: column;
              justify-content: center;
              align-items: center;
              .iconfont {
                font-size: 40px;
                margin: 20px 0 10px;
              }
            }
          }
        }
      }
    }
    .table-container {
      width: 100%;
      height: calc(100% - 300px);
      background-color: $mainBg;
      padding: 10px 20px;
      margin-top: 20px;
      overflow: hidden;
      .search-container {
        width: 100%;
        height: 60px;
        display: flex;
        justify-content: flex-start;
        align-items: center;
        .title {
          display: inline-block;
          width: 200px;
          font-weight: bold;
          font-size: 16px;
        }
        .search-content {
          width: 400px;
          display: flex;
          justify-content: flex-start;
          align-items: center;
          label {
            font-size: 14px;
          }
          /deep/ .el-input {
            width: 300px;
          }
        }
      }
      .table-content {
        width: 100%;
        height: calc(100% - 100px);
        /deep/ .el-table__body-wrapper {
          height: 100%;
          padding-bottom: 46px;
          overflow-y: auto;
        }
        .img-contianer {
          width: 100px;
          height: 60px;
          position: relative;
          .img-icon {
            position: absolute;
            bottom: -2px;
            right: 0;
            font-size: 24px;
            color: $mainColor;
            span {
              position: absolute;
              top: calc(50% - 8px);
              left: calc(50% - 4px);
              font-weight: bold;
              font-size: 16px;
            }
          }
        }
        /deep/ .img {
          width: 100px;
          height: 60px;
        }
        .iconfont {
          cursor: pointer;
        }
      }
    }
  }
</style>
